<template>
	<page-meta :page-style="'overflow:hidden'">
		<gzPageWrapper
			ref="gzPageWrapperRef"
			:styles="{ background: 'radial-gradient(closest-side at 50% 30%, #F5F6FA, transparent),conic-gradient(from 45deg at 50% 20%, #FCF9EF, #FEF4F4, #F5F6FA, #F5F6FA, #F5F6FA, #F5F6FA, #DCF7EE, #D9F6EC, #F1F9F0, #FAFAEC)' }"
			:up="{ use: true, auto: false, isLock: true, empty: { use: false } }"
			:down="{ auto: false, }"
			:nav="{ title: '首页' }"
			@upCallback="upCallback"
		>
			<template #default>
				<view class="inner" style="padding:0 24rpx 40rpx">
					<!-- 机构选择模块 -->
					<AgentDisplay v-if="isProvincialLevelLite" ref="agentDisplayRef" @rightClickHandle="onLeftClickHandle"/>
					<view class="swiper">
						<uni-swiper-dot class="uni-swiper-dot-box" :info="vdata.info" :current="vdata.current" :mode="vdata.mode" :dots-styles="vdata.dotsStyles" field="content">
							<swiper class="swiper-box" circular @change="swiperChange" :current="vdata.current" autoplay :interval="3000">
								<swiper-item class="swiper-box-item" v-for="(item, index) in vdata.info" :key="index">
									<image style="height: 100%;width: 100%;" :src="item.url" mode="scaleToFill" @click="onBanner(item)"></image>
								</swiper-item>
							</swiper>
						</uni-swiper-dot>
					</view>
					<!-- #ifndef MP-ZYX -->
					<!-- 金融服务模块 -->
					<FinancialServicesList />
					<MemberBenefits :awards="awards" v-model:tabIndex="currentTabIndexRef" @tabsChange="tabsChange" @clickHandle="clickHandle"/>
					<!-- #endif -->
					<!-- 精彩活动 -->
					<view class="activity-wrap" v-if="vdata.activityListWonderful?.length">
						<view class="title">精彩活动</view>
						<view class="list">
							<view class="item" v-for="item in vdata.activityListWonderful" :key="item.activityImg" @tap="jumpWebview(item.url)">
								<image :src="item.activityImg"></image>
							</view>
						</view>
					</view>
					<!-- 活动模块 -->
					<view class="activity-wrap" v-if="vdata.activityListOther?.length">
						<view class="title">热门活动</view>
						<view class="list">
							<view class="item" v-for="item in vdata.activityListOther" @tap="toUrl(`?activityId=${item.activityId}&from=${0}`)">
								<image :src="item.activityImg || item.templateImg"></image>
							</view>
						</view>
					</view>
					<view class="activity-wrap" v-if="vdata.activityListMch?.length">
						<view class="title">商家活动</view>
						<view class="list">
							<view class="item" v-for="item in vdata.activityListMch" @tap="toUrl(`?activityId=${item.activityId}&from=${0}`)">
								<image :src="item.activityImg || item.templateImg"></image>
							</view>
						</view>
					</view>
					<gzListNull v-if="!vdata.activityListOther?.length && !vdata.activityListMch?.length && !vdata.activityListWonderful?.length" :list="[]" :text="'暂未开展活动'"></gzListNull>
				</view>
			</template>
		</gzPageWrapper>
	</page-meta>
	<!-- 实名提示弹窗 -->
	<uni-popup ref="authPopupRef" type="dialog" :is-mask-click="false">
		<view class="auth-popup-container">
			<view :style="activityJson?.wrapper?.style">
				<view :style="activityJson?.btn?.style" class="btn" @click="toRealNamePage">
				</view>
			</view>
			<image src="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/29468fff-b147-43d9-a057-47cdd8b5b588.png" mode="" @click="() => authPopupRef.close()"></image>
		</view>
	</uni-popup>
	<!-- 授权登录弹窗 -->
	<gzLoginPopup ref="gzLoginPopupRef" v-model:value="vdata.fansInfo" v-model:isLogin="vdata.isLogin"></gzLoginPopup>
</template>

<script setup>
	// #ifndef MP-ZYX
	// 金融服务模块
	import FinancialServicesList from '@/pages/index/components/FinancialServicesList.vue'
	import MemberBenefits from '@/pages/index/components/MemberBenefits.vue'
	// #endif
	import AgentDisplay from '@/pages/index/components/AgentDisplay.vue'
	import scoreMall from '../pageBlessingPoints/components/scoreMall.vue'
	import tool from '@/util/tool.js'
	import storageManage from '@/util/storageManage.js'
	import appConfig from '@/config/appConfig.js'
	import { ref, reactive, onMounted, nextTick, getCurrentInstance, computed } from 'vue';
	import { onShow, onLoad, onPageScroll, onHide } from '@dcloudio/uni-app';
	import { $liteBannerList, $fansDetail, $activityList, $checkActivity, $memberBenefitsAwards, $memberBenefitsGet, $getMchCcCoupon, $checkUserPayAuthMch, $getMchCoupon } from '@/http/apiManager.js';
	import { navigateTo } from '@/util/interceptors.js'
	import dayjs from 'dayjs'
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

	const gzLoginPopupRef = ref()
	const gzPageWrapperRef = ref()
	const authPopupRef = ref()
	const agentDisplayRef = ref()
	
	const fansId = storageManage.fansId()
	const userId = storageManage.userId()

	const vdata = reactive({
		isLogin: false,	// 用户登录状态
		fansInfo: {},	// 用户信息
		info: [], // 轮播图信息
		current: 0,
		mode: 'dot',
		dotsStyles: {
			backgroundColor: 'rgba(255,255,255,0.30)',
			border: '1px rgba(255,255,255,0.30) solid',
			color: '#fff',
			selectedBackgroundColor: 'rgba(255,255,255,0.80)',
			selectedBorder: '1px rgba(255,255,255,0.80); solid'
		},
		
		activityListWonderful: [	// 精彩活动
			// #ifdef MP-YHDD
			{ activityName: '惊喜周周团', activityImg: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/fa18b889-b815-4288-9f74-52b66858be39.png', url: `/pages/common/webview/index?url=${encodeURIComponent('https://jlyxlite.jdyd.xyz/activity/groupon_weekly.html')}` },
			{ activityName: '欢乐周周游', activityImg: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/dbeb68e3-f445-40c1-bc5c-4cf190f20a71.png', url: `/pages/common/webview/index?url=${encodeURIComponent('https://jlyxlite.jdyd.xyz/activity/travel_weekly.html')}` },
			{ activityName: '特价薅羊毛', activityImg: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/74007d78-ad31-45fa-a623-22d31be8a87d.png', url: `/pages/common/webview/index?url=${encodeURIComponent('https://jlyxlite.jdyd.xyz/activity/shopping_deals.html')}` },		
			// #endif
			// #ifndef MP-YHDD
			{ activityName: '吃喝邮乐周周游', activityImg: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/d9e40459-cf6c-4e01-965f-da101e6ab465.png', url: `/pages/common/webview/index?url=${encodeURIComponent('https://zyx.post183.net/zyxfans/resources/html/travel_weekly.html')}` },
			// #endif
		],
		
		activityList: [], // 活动列表
		activityListOther: [],	// 热门活动
		activityListMch: [],	// 商家活动
		
		// 引导实名所需参数
		activityId: '',
		activityTemplateNo: ''
	});
	
	const gettingCouponInfo = ref(null)
	
	const activityJson = ref({
		"wrapper":{
			"style":{
				"width":"620rpx",
				"height":"564rpx",
				"background":"url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/3cdcdfb4-95bf-4ba0-9bf9-c17db390132f.png') no-repeat left top / 100% 100%"
			}
		},
		"btn":{
			"style":{
				"width":"300rpx",
				"height":"100rpx"
			}
		}
	})
	
	// 是否是省级小程序
	const isProvincialLevelLite = computed(() => {
		if(appConfig.level === 0){
			return true
		}
		return false
	})
	
	onLoad(async ({ memberBenefitsIndex, item }) => {
		// 注册定位信息通知 用于更新定位信息
		uni.$on('UPDATE_AGENT_INFO',onUpdateAgentInfoHandle)
		// 初始化 活动列表 活动轮播图 全区会员福利奖品列表 引导用户实名
		if(item){
			currentTabIndexRef.value = Number(memberBenefitsIndex)
			gettingCouponInfo.value = JSON.parse(decodeURIComponent(item))
		}
		nextTick(() => {
			gzPageWrapperRef.value.getMescroll().resetUpScroll()
		})
	})
	
	onShow(() => {
		vdata.isLogin = storageManage.isLogin()
	})
	
	onHide(() => {
		// 关闭引导实名弹窗
		authPopupRef.value.close()
	})
	
	// 定位信息更新事件处理（更新活动列表）
	async function onUpdateAgentInfoHandle(e){
		// 更新位置显示
		agentDisplayRef.value.onChangeAgentInfo(e)
		// 重新拉取奖品列表和banner列表
		uni.showLoading({ title: '加载中...', mask: true})
		await getLiteBannerList()
		await getActivityList()
		uni.hideLoading()
	}
	
	// 跳转机构索引页
	function onLeftClickHandle(){
		uni.navigateTo({
			url: '/pages/agentSelect/agentSelect'
		})
	}
	
	// 请求奖品列表
	const awards = ref([])
	async function getAwards(){
		const { bizData } = await $memberBenefitsAwards()
		awards.value = bizData
	}
	// 商家券
	async function getMchAwards(){
		const { bizData } = await $getMchCcCoupon()
		awards.value = bizData
	}
	// tabs切换
	const currentTabIndexRef = ref(0)	// v-model双向绑定
	async function tabsChange(){
		if(currentTabIndexRef.value === 0){	// 全区会员福利
			await getAwards()
		}else if(currentTabIndexRef.value === 1){	// 区域专享
			awards.value = []
		}else{	// 商家券
			await getMchAwards()
		}
		uni.hideLoading()
	}
	/**
	 * 全区会员福利兑换接口
	 */
	async function clickHandle(info){
		const { activityId, awardType, couponId:awardId, numberSheets } = info
		// 校验用户出资方授权
		uni.showLoading({ title: '领取中...', mask: true })
		const { bizData:payAuthBizData } = await $checkUserPayAuthMch({ awardId })
		const { flag, url, ifCode } = payAuthBizData
		if(url && ifCode){	// 说明用户未授权
			// 跳转授权页面
			appConfig.url = url
			getApp().globalData.temp_path = `/pages/index/index?type=tabbar&memberBenefitsIndex=${currentTabIndexRef.value}&item=${encodeURIComponent(JSON.stringify(info))}`
			getApp().globalData.temp_ifcode = ifCode
			uni.reLaunch({
				url: '/pages/openid/openid'
			})
			uni.hideLoading()
			return
		}
		// 校验奖品剩余当前剩余数量
		if(numberSheets <= 0){
			$infoBox.toast('当前时段已抢光')
			return
		}
		if(currentTabIndexRef.value === 0){	// 全区会员福利
			await $memberBenefitsGet({ awardId, activityId, awardType })
		}else if(currentTabIndexRef.value === 1){	// 区域专享
			
		}else{	// 商家券
			await $getMchCoupon({ awardId, activityId, awardType })
		}
		// 刷新列表
		await tabsChange()
		$infoBox.toast('领取成功！')
	}
	
	/**
	 * 跳转webview页面
	 */
	function jumpWebview(url){
		getApp().preventActive(()=>{
			// 判断用户是否登录
			// if(!vdata.isLogin){
			// 	return gzLoginPopupRef.value.open()	// 打开授权弹框
			// }
			uni.navigateTo({
				url
			})
		})
	}

	/**
	 * 活动页面跳转
	 */
	function toUrl(url) {
		getApp().preventActive(()=>{
			// 判断用户是否登录
			if(!vdata.isLogin){
				return gzLoginPopupRef.value.open()	// 打开授权弹框
			}
			navigateTo({url})
		})
	}
	/**
	 * 引导实名活动
	 */
	async function leadRealnameActivity(){
		if(storageManage.userInfo()){
			vdata.fansInfo = storageManage.userInfo()
		}else{
			const { bizData:fansInfo } = await $fansDetail()
			vdata.fansInfo = fansInfo
			if(vdata.isLogin){	// 如果用户登录 本地缓存用户信息
				storageManage.userInfo(fansInfo)
			}
		}
		
		// 首先判断用户是否处于 已实名 状态
		if(vdata.fansInfo.isAuth === 0){	// 用户已是实名状态 不进行提示
			return
		}
		// 判断是否存在 实名奖励活动
		const { bizData } = await $checkActivity()
		if(bizData === 0){	// 不存在引导实名活动 不进行提示
			return
		}
		// 存在引导实名活动 拿取活动id以及活动模板编号
		vdata.activityId = bizData.activityId
		vdata.activityTemplateNo = bizData.activityTemplateNo
		
		// 判断用户是否实名
		const TIPS_TYPE = 'week';	// 提示类型 日day 周week 月month
		const TIPS_TIMES = 2;	// 提示次数
		const TIPS_LAST_TIME = uni.getStorageSync('TIPS_LAST_TIME');	// 上次提示时间
		const TIPS_TIMES_ED = uni.getStorageSync('TIPS_TIMES_ED') || 0;	// 已经提示次数
		
		let showPopupLimit = false;	// 在时间以及次数上是否展示实名弹窗
		
		// 周比较特殊 需要单独判断是否是同一周
		if(TIPS_TYPE === 'week'){
			if(dayjs(TIPS_LAST_TIME).subtract(1,'day').isSame(dayjs().subtract(1,'day'),'week')){	// 在一个周期
				if(TIPS_TIMES_ED < TIPS_TIMES){	// 没有达到提示上限
					// 记录时间 以及次数
					uni.setStorageSync('TIPS_LAST_TIME',dayjs().format('YYYY-MM-DD'))
					uni.setStorageSync('TIPS_TIMES_ED',TIPS_TIMES_ED + 1)
					showPopupLimit = true
				}
			}else{	// 不在同一周期
				uni.setStorageSync('TIPS_LAST_TIME',dayjs().format('YYYY-MM-DD'))
				uni.setStorageSync('TIPS_TIMES_ED',1)
				showPopupLimit = true
			}
		}else{
			if(dayjs(TIPS_LAST_TIME).isSame(dayjs(),TIPS_TYPE)){
				if(TIPS_TIMES_ED < TIPS_TIMES){	// 没有达到提示上限
					// 记录时间 以及次数
					uni.setStorageSync('TIPS_LAST_TIME',dayjs().format('YYYY-MM-DD'))
					uni.setStorageSync('TIPS_TIMES_ED',TIPS_TIMES_ED + 1)
					showPopupLimit = true
				}
			}else{	// 不在同一周期
				uni.setStorageSync('TIPS_LAST_TIME',dayjs().format('YYYY-MM-DD'))
				uni.setStorageSync('TIPS_TIMES_ED',1)
				showPopupLimit = true
			}
		}
		// 判断提示 周期以及次数 是否符合
		if(!showPopupLimit){
			return
		}
		// 实名状态 实名奖励活动 弹窗周期以及次数 全部符合条件 进行弹窗提示
		nextTick(() => {
			authPopupRef.value.open()
		})
	}
	
	/**
	 * 跳转实名认证
	 */
	function toRealNamePage(){
		// 判断用户是否登录
		if(!vdata.isLogin){
			return gzLoginPopupRef.value.open()	// 打开授权弹框
		}
		// 从index跳转实名 即是从引导实名弹窗跳转实名需要 在实名接口多传递两个参数activityTemplateNo和activityId
		uni.navigateTo({
			url: `/pageUser/realName/index?activityId=${vdata.activityId}&activityTemplateNo=${vdata.activityTemplateNo}`,
			success() {
				authPopupRef.value.close()
			}
		})
	}
	/**
	 * 获取轮播图信息
	 */
	async function getLiteBannerList() {
		const { bizData } = await $liteBannerList({ agentNo: storageManage.agentInfo().agentNo })
		vdata.info = bizData.records
	}
	/**
	 * 轮播图切换
	 */
	function swiperChange ({ detail }){
		let {current, source} = detail
		//只有页面自动切换，手动切换时才轮播，其他不允许
		if(source === 'autoplay' || source === 'touch'){
			vdata.current = current
		}
	}
	/**
	 * 点击Banner
	 */
	function onBanner(item) {
		// 判断用户是否登录
		if(!vdata.isLogin && (item.linkType == '1' || item.linkType == '2' )){
			return gzLoginPopupRef.value.open()	// 打开授权弹框
		}
		switch (item.linkType) {
			case '1':
				// 活动详情
				// this.$tab.navigateTo('/pages/shopDetail/shopDetail?productUuid=' + item.content)
				break;
			case '2':
				// 页面路径
				uni.navigateTo({
					url: item.content
				})
				// this.$tab.navigateTo(item.content)
				break;
			case '3':
				// 网页
				uni.navigateTo({
					url: '/pages/common/webview/index?url=' + encodeURIComponent(item.content)
				})
				break;
			default:
				break;

		}

	}
	/**
	 * 获取活动列表
	 */
	async function getActivityList() {
		const { bizData } = await $activityList({ agentNo: storageManage.agentInfo().agentNo })
		const tempActivityListMch = []
		const tempActivityListOther = []
		bizData.forEach(item => {
			if(item.entryway.includes('4')){
				tempActivityListMch.push(item)
			}else{
				tempActivityListOther.push(item)
			}
		})
		vdata.activityListMch = tempActivityListMch
		vdata.activityListOther = tempActivityListOther
	}
	/**
	 * 下拉刷新
	 */
	async function upCallback(mescroll){
		mescroll.hideUpScroll()	// 隐藏上拉加载的布局
		try{
			uni.showLoading({ title: '加载中...' })
			await Promise.all([getLiteBannerList(),tabsChange(),getActivityList()])
			uni.hideLoading()
			// 自动领取卡券
			if(gettingCouponInfo.value !== null){
				await clickHandle(gettingCouponInfo.value)
				// 重置为null
				gettingCouponInfo.value = null
			}
			await leadRealnameActivity()	// 当前请求不展示loading
			mescroll.endSuccess(0)
		}catch(e){
			// 重置为null
			gettingCouponInfo.value = null
			mescroll.endErr()
		}
	}
</script>

<style scoped lang="less">
	.fans-card {
		border: 4rpx solid #fff;
		padding: 40rpx 32rpx;
		background: linear-gradient(to bottom, #E1F8EF 0%, #E1F8EF 10%, #ECFAF5 20%, #fff 100%);
		// background: conic-gradient( from -90deg at 50% 0%,  0%, #FFFFFF 48%, #FFFFFF 100%);
		border-radius: 12rpx;
		margin: 24rpx 0;
	
		.top {
			display: flex;
			gap: 16rpx;
			align-items: center;
	
			image {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				border: 2rpx solid #fff;
			}
	
			.name {
				font-size: 32rpx;
				color: #333333;
				font-weight: bold;
			}
	
			.tag {
				background: #545C7D;
				border-radius: 12rpx;
				padding: 0 12rpx;
				display: flex;
				align-items: center;
				gap: 5rpx;
	
				text {
					font-size: 20rpx;
					color: #FFFFFF;
				}
			}
		}
	
		.bottom {
			display: flex;
			margin-top: 36rpx;
	
			.block {
				width: 50%;
	
				&:nth-child(2) {
					border-left: 1rpx solid #eee;
					padding-left: 30rpx;
					box-sizing: border-box;
				}
	
				.title-wrap {
					display: flex;
					align-items: center;
					gap: 8rpx;
	
					image {
						width: 36rpx;
						height: 36rpx;
					}
	
					text {
						font-size: 28rpx;
						color: #333333;
					}
				}
	
				.num-btn {
					display: flex;
					gap: 20rpx;
					align-items: center;
					margin-top: 10rpx;
	
					view {
						&:nth-child(1) {
							font-weight: bold;
							font-size: 48rpx;
							color: #333333;
						}
	
						&:nth-child(2) {
							font-size: 24rpx;
							color: #333333;
							padding: 12rpx 24rpx;
							background: #def7ee;
							border-radius: 30rpx;
						}
					}
				}
			}
		}
	}
	
	.activity-wrap {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 44rpx 0;
		margin-top: 24rpx;
	
		.title {
			font-weight: bold;
			font-size: 34rpx;
			margin-bottom: 44rpx;
			padding: 0 32rpx;
		}
	
		.list {
			display: flex;
			flex-direction: column;
			gap: 24rpx;
	
			.item {
	
				image {
					width: 100%;
					height: 395rpx;
					border-radius: 20rpx;
				}
			}
	
		}
	}

	.swiper-box {
		height: 396rpx;
	}

	.swiper-box-item {
		border-radius: 20rpx;

		.swiper-item {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: column;
			justify-content: center;
			align-items: center;
			height: 380rpx;
			color: #fff;
		}

		.swiper-item0 {
			background-color: #cee1fd;
		}

		.swiper-item1 {
			background-color: #b2cef7;
		}

		.swiper-item2 {
			background-color: #cee1fd;
		}
	}


	.image {
		width: 750rpx;
	}

	/* #ifndef APP-NVUE */
	::v-deep .image img {
		-webkit-user-drag: none;
		-khtml-user-drag: none;
		-moz-user-drag: none;
		-o-user-drag: none;
		user-drag: none;
	}

	/* #endif */
	.uni-swiper-dot-box {
		width: 100%;
		display: block;
		margin: 0 auto;
	}

	.uni-bg-red {
		background-color: #ff5a5f;
	}

	.uni-bg-green {
		background-color: #09bb07;
	}

	.uni-bg-blue {
		background-color: #007aff;
	}

	.swiper {
		// padding-top: 40rpx;
		// background-image: linear-gradient(180deg, #2C7244 0%, #F4F4F4 60%);
	}
	
	.auth-popup-container{
		text-align: center;
		display: flex;
		flex-direction: column;
		gap: 60rpx;
		align-items: center;
		
		&>view{
			height: 564rpx;
			width: 620rpx;
			background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/3cdcdfb4-95bf-4ba0-9bf9-c17db390132f.png') no-repeat left top / 100% 100%;
			position: relative;
			.btn{
				width: 300rpx;
				height: 100rpx;
				position: absolute;
				bottom: 30rpx;
				left: 50%;
				transform: translateX(-50%);
			}
		}
		image{
			width: 68rpx;
			height: 68rpx;
		}
	}
</style>